package com.handu.luna.boss.controller;


import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;

import javax.validation.Valid;

import com.handu.luna.core.domain.order.OrderOperator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMethod;

import com.handu.luna.core.domain.order.OrderInfo;
import com.handu.luna.core.domain.search.OrderSearch;


@Controller
@RequestMapping("/orderInfo/*")
public class OrderInfoController extends BaseController{
	
	@RequestMapping(method = RequestMethod.GET)
	public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"id"},direction = Sort.Direction.ASC) Pageable pageable) throws UnsupportedEncodingException{
		OrderSearch search ;
		if(viewState != null && !viewState.trim().equals("") && !viewState.equals("-1")){
			//解析传递过来的查询json字符串
			search = (OrderSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), OrderSearch.class);
			return createModel()
					.add("orderInfos", context.getOrderInfoRepository().findAll(OrderInfo.searchByCondition(search),pageable))
					.add("viewState", viewState)
					.add("orderSearch", search);
		}else{
			search = new OrderSearch();
            @SuppressWarnings("unused")
			Page<OrderInfo> infos = context.getOrderInfoRepository().findAllParent(pageable);
			return createModel()
					.add("orderInfos", context.getOrderInfoRepository().findAllParent(pageable))
					.add("orderSearch", search)
					.add("viewState", "");
		}
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public BossModel index(OrderSearch orderSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"id"},direction = Sort.Direction.ASC) Pageable pageable) throws UnsupportedEncodingException{
		return createModel()
				.add("orderInfos", context.getOrderInfoRepository().findAll(OrderInfo.searchByCondition(orderSearch),pageable))
				.add("orderSearch", orderSearch)
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(orderSearch).toString().getBytes("UTF-8")));
	}

    @RequestMapping(value = "listChilds",method = RequestMethod.POST)
    public @ResponseBody JSONArray list(String parentNumber){
        List<OrderInfo> childs = context.getOrderInfoRepository().findAllChildsByOrderNumber(parentNumber);
        return JSONArray.fromObject(convertFromListToJson(childs));
    }

    private String convertFromListToJson(List<OrderInfo> list){
        StringBuffer buffer = new StringBuffer("[");
        for (int i = 0; i< list.size();i++){
            buffer.append("{\"id\":\""+list.get(i).getId()+"\",");
            buffer.append("\"orderNumber\":\""+list.get(i).getOrderNumber()+"\",");
            buffer.append("\"orderAmount\":\"￥" + list.get(i).getOrderAmount() + "\",");//list.get(i).getOrderAmount()
            buffer.append("\"paymentAmount\":\"￥"+(list.get(i).getPaymentAmount() == null ? 0.0 :list.get(i).getPaymentAmount())+"\",");//list.get(i).getPaymentAmount()
            buffer.append("\"orderState\":\""+list.get(i).getParentOrder().getOrderStatus().description+","+list.get(i).getParentOrder().getPaymentStatus().description+","+list.get(i).getDeliveryStatus().description+"\",");
            buffer.append("\"operator\":\"/orderInfo/view/"+list.get(i).getId()+"\"},");
        }
        buffer.deleteCharAt(buffer.length()-1);
        buffer.append("]");
        return  buffer.toString();
    }


	
	@RequestMapping(value="view/{id}/{page}/{viewState}")
	public BossModel view(@PathVariable long id,@PathVariable long page,@PathVariable String viewState){
		return createModel("orderInfo/info")
				.add("orderInfo", context.getOrderInfoRepository().findOne(id))
				.add("viewState", viewState)
				.add("page", page)
                .add("orderOperations",context.getOrderOperatorRepository().findAll(id));
	}
	
	@RequestMapping(value="edit/{id}/{page}/{viewState}")
	public BossModel edit(@PathVariable long id,@PathVariable long page,@PathVariable String viewState){
		
		return createModel("orderInfo/save")
				.add("orderInfo", context.getOrderInfoRepository().findOne(id))
				.add("viewState", viewState)
				.add("page", page);
	}

    @RequestMapping(value = "operator/{orderInfoId}/{status}/{isParent}")
    public BossModel operator(@PathVariable long orderInfoId, @PathVariable String status,@PathVariable boolean isParent,
                              String viewState , String page , String shipping){
        String[] statusArr = status.split("_");
        OrderOperator operator = new OrderOperator(orderInfoId,isParent,statusArr[0],statusArr[1],statusArr[2]);
        return createModel("orderInfo/operator").add("orderOperator",operator)
                .add("viewState",viewState)
                .add("page",page)
                .add("shipping",shipping == null ?"":shipping);
    }

    @RequestMapping(value = "saveOperator/{page}/{viewState}")
    public BossModel saveOperator(OrderOperator orderOperator ,@PathVariable long page,@PathVariable String viewState ){
        context.getOrderInfoRepository().findOne(orderOperator.getOrderId()).changeStatus(orderOperator);

        return createModel("orderInfo/info").add("orderInfo", context.getOrderInfoRepository().findOne(orderOperator.getOrderId()))
                .add("viewState", viewState)
                .add("page", page)
                .add("orderOperations",context.getOrderOperatorRepository().findAll(orderOperator.getOrderId()));
    }


	@RequestMapping(value="save/{page}/{viewState}",method=RequestMethod.POST)
	@InitBinder(value={"freightAmount","serviceNote"})
	public BossModel save(@Valid OrderInfo orderInfo,BindingResult bindingResult,ModelMap model,
			@PathVariable long page,@PathVariable String viewState){
		
		if(bindingResult.hasErrors()){
			return createModel("orderInfo/save").add("orderInfo", orderInfo);
		}
		orderInfo.updateOrderInfo();
		return createModel("orderInfo/info").add("orderInfo", context.getOrderInfoRepository().findOne(orderInfo.getId()))
				.add("viewState", viewState)
				.add("page", page)
                .add("orderOperations",context.getOrderOperatorRepository().findAll(orderInfo.getId()));
		
	}
	

}
